// 用户端语言切换组件
class UserLanguageSwitcher extends HTMLElement {
    constructor() {
        super();
        this.currentLanguage = 'zh-CN';
        this.availableLanguages = [
            { code: 'zh-CN', name: '简体中文', flag: '🇨🇳' },
            { code: 'zh-TW', name: '繁體中文', flag: '🇨🇳' },
            { code: 'en-US', name: 'English', flag: '🇺🇸' },
            { code: 'en-GB', name: 'English (UK)', flag: '🇬🇧' },
            { code: 'ja-JP', name: '日本語', flag: '🇯🇵' },
            { code: 'ko-KR', name: '한국어', flag: '🇰🇷' },
            { code: 'fr-FR', name: 'Français', flag: '🇫🇷' },
            { code: 'de-DE', name: 'Deutsch', flag: '🇩🇪' },
            { code: 'es-ES', name: 'Español', flag: '🇪🇸' },
            { code: 'es-MX', name: 'Español (México)', flag: '🇲🇽' },
            { code: 'pt-BR', name: 'Português (Brasil)', flag: '🇧🇷' },
            { code: 'pt-PT', name: 'Português (Portugal)', flag: '🇵🇹' },
            { code: 'ru-RU', name: 'Русский', flag: '🇷🇺' },
            { code: 'ar-SA', name: 'العربية', flag: '🇸🇦' },
            { code: 'hi-IN', name: 'हिन्दी', flag: '🇮🇳' },
            { code: 'th-TH', name: 'ไทย', flag: '🇹🇭' },
            { code: 'vi-VN', name: 'Tiếng Việt', flag: '🇻🇳' }
        ];
    }

    connectedCallback() {
        this.render();
        this.attachEventListeners();
        this.loadLanguageSettings();
    }

    render() {
        const currentLang = this.availableLanguages.find(lang => lang.code === this.currentLanguage);
        
        this.innerHTML = `
            <div class="user-language-switcher">
                <div class="language-dropdown">
                    <button class="language-btn" type="button" aria-label="切换语言">
                        <span class="flag">${currentLang.flag}</span>
                        <span class="language-name">${currentLang.name}</span>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="language-menu">
                        ${this.availableLanguages.map(lang => `
                            <div class="language-item ${lang.code === this.currentLanguage ? 'active' : ''}" 
                                 data-lang="${lang.code}" role="option">
                                <span class="flag">${lang.flag}</span>
                                <span class="language-name">${lang.name}</span>
                                ${lang.code === this.currentLanguage ? '<i class="fas fa-check"></i>' : ''}
                            </div>
                        `).join('')}
                    </div>
                </div>
            </div>
            
            <style>
                .user-language-switcher {
                    position: relative;
                    display: inline-block;
                }
                
                .language-btn {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    padding: 8px 12px;
                    background: #f8f9fa;
                    border: 1px solid #dee2e6;
                    border-radius: 6px;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    font-size: 14px;
                    color: #495057;
                }
                
                .language-btn:hover {
                    background: #e9ecef;
                    border-color: #adb5bd;
                }
                
                .language-menu {
                    position: absolute;
                    top: 100%;
                    right: 0;
                    background: white;
                    border: 1px solid #dee2e6;
                    border-radius: 6px;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                    min-width: 140px;
                    z-index: 1000;
                    display: none;
                    margin-top: 4px;
                }
                
                .language-menu.show {
                    display: block;
                }
                
                .language-item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 10px 12px;
                    cursor: pointer;
                    transition: background-color 0.2s ease;
                    font-size: 14px;
                }
                
                .language-item:hover {
                    background: #f8f9fa;
                }
                
                .language-item.active {
                    background: #e7f3ff;
                    color: #007bff;
                }
                
                .language-info {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }
                
                .flag {
                    font-size: 16px;
                }
                
                .language-name {
                    font-weight: 500;
                }
                
                .fa-check {
                    color: #28a745;
                    font-size: 12px;
                }
                
                @media (max-width: 768px) {
                    .language-btn {
                        padding: 6px 10px;
                        font-size: 13px;
                    }
                    
                    .language-name {
                        display: none;
                    }
                    
                    .language-menu {
                        right: -50px;
                    }
                }
            </style>
        `;
    }

    attachEventListeners() {
        const btn = this.querySelector('.language-btn');
        const menu = this.querySelector('.language-menu');
        const items = this.querySelectorAll('.language-item');

        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            menu.classList.toggle('show');
        });

        items.forEach(item => {
            item.addEventListener('click', (e) => {
                e.stopPropagation();
                const langCode = item.dataset.lang;
                this.switchLanguage(langCode);
                menu.classList.remove('show');
            });
        });

        // 点击外部关闭菜单
        document.addEventListener('click', (e) => {
            if (!this.contains(e.target)) {
                menu.classList.remove('show');
            }
        });

        // ESC键关闭菜单
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                menu.classList.remove('show');
            }
        });
    }

    async switchLanguage(langCode) {
        if (langCode === this.currentLanguage) return;

        try {
            // 调用API切换语言
            const response = await fetch('/api/i18n/set-language', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ language: langCode })
            });

            if (response.ok) {
                this.currentLanguage = langCode;
                this.saveLanguageSettings();
                
                // 触发语言切换事件
                this.dispatchEvent(new CustomEvent('languageChanged', {
                    detail: { language: langCode }
                }));

                // 重新加载页面内容
                this.reloadPageContent();
            }
        } catch (error) {
            console.error('切换语言失败:', error);
            // 即使API失败，也更新UI和本地设置
            this.currentLanguage = langCode;
            this.saveLanguageSettings();
            this.reloadPageContent();
        }
    }

    loadLanguageSettings() {
        // 从localStorage获取保存的语言设置
        const savedLang = localStorage.getItem('user-language') || 'zh-CN';
        
        // 从URL参数获取语言设置（优先级更高）
        const urlParams = new URLSearchParams(window.location.search);
        const urlLang = urlParams.get('lang');
        
        if (urlLang && this.availableLanguages.some(lang => lang.code === urlLang)) {
            this.currentLanguage = urlLang;
        } else {
            this.currentLanguage = savedLang;
        }
        
        this.render();
        this.updatePageLanguage();
    }

    saveLanguageSettings() {
        localStorage.setItem('user-language', this.currentLanguage);
        
        // 更新URL参数（不刷新页面）
        const url = new URL(window.location);
        url.searchParams.set('lang', this.currentLanguage);
        window.history.replaceState({}, '', url);
    }

    updatePageLanguage() {
        // 更新html标签的lang属性
        document.documentElement.lang = this.currentLanguage;
        
        // 更新页面标题（支持17种语言）
        const titleMap = {
            'zh-CN': 'Ubike - 电动自行车商城',
            'zh-TW': 'Ubike - 電動自行車商城',
            'en-US': 'Ubike - Electric Bike Store',
            'en-GB': 'Ubike - Electric Bike Store',
            'ja-JP': 'Ubike - 電動自転車ストア',
            'ko-KR': 'Ubike - 전기 자전거 스토어',
            'fr-FR': 'Ubike - Magasin de vélos électriques',
            'de-DE': 'Ubike - Elektrofahrrad-Geschäft',
            'es-ES': 'Ubike - Tienda de bicicletas eléctricas',
            'es-MX': 'Ubike - Tienda de bicicletas eléctricas',
            'pt-BR': 'Ubike - Loja de bicicletas elétricas',
            'pt-PT': 'Ubike - Loja de bicicletas elétricas',
            'ru-RU': 'Ubike - Магазин электровелосипедов',
            'ar-SA': 'Ubike - متجر الدراجات الكهربائية',
            'hi-IN': 'Ubike - इलेक्ट्रिक बाइक स्टोर',
            'th-TH': 'Ubike - ร้านจักรยานไฟฟ้า',
            'vi-VN': 'Ubike - Cửa hàng xe đạp điện'
        };
        
        if (titleMap[this.currentLanguage]) {
            document.title = titleMap[this.currentLanguage];
        }
    }

    reloadPageContent() {
        this.updatePageLanguage();
        
        // 触发页面内容重新加载（实际项目中应该使用i18n库）
        this.dispatchEvent(new CustomEvent('contentReload', {
            detail: { language: this.currentLanguage }
        }));
        
        // 显示语言切换提示
        this.showLanguageChangeToast();
    }

    showLanguageChangeToast() {
        const messages = {
            'zh-CN': '语言已切换为简体中文',
            'zh-TW': '語言已切換為繁體中文',
            'en-US': 'Language switched to English',
            'en-GB': 'Language switched to English',
            'ja-JP': '言語が日本語に切り替わりました',
            'ko-KR': '언어가 한국어로 전환되었습니다',
            'fr-FR': 'Langue changée en français',
            'de-DE': 'Sprache auf Deutsch geändert',
            'es-ES': 'Idioma cambiado a español',
            'es-MX': 'Idioma cambiado a español',
            'pt-BR': 'Idioma alterado para português',
            'pt-PT': 'Idioma alterado para português',
            'ru-RU': 'Язык изменен на русский',
            'ar-SA': 'تم تغيير اللغة إلى العربية',
            'hi-IN': 'भाषा हिंदी में बदली गई',
            'th-TH': 'เปลี่ยนภาษาเป็นภาษาไทยแล้ว',
            'vi-VN': 'Đã chuyển đổi ngôn ngữ sang tiếng Việt'
        };
        
        const message = messages[this.currentLanguage] || 'Language changed';
        
        // 创建提示消息
        const toast = document.createElement('div');
        toast.className = 'language-toast';
        toast.innerHTML = `
            <div class="toast-content">
                <i class="fas fa-check-circle"></i>
                <span>${message}</span>
            </div>
            <style>
                .language-toast {
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #28a745;
                    color: white;
                    padding: 12px 16px;
                    border-radius: 6px;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                    z-index: 9999;
                    animation: slideIn 0.3s ease;
                }
                
                .toast-content {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }
                
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
            </style>
        `;
        
        document.body.appendChild(toast);
        
        // 3秒后自动移除
        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    // 获取当前语言
    getCurrentLanguage() {
        return this.currentLanguage;
    }

    // 获取可用语言列表
    getAvailableLanguages() {
        return this.availableLanguages;
    }

    // 设置语言（外部调用）
    setLanguage(langCode) {
        if (this.availableLanguages.some(lang => lang.code === langCode)) {
            this.switchLanguage(langCode);
        }
    }
}

// 注册自定义元素
customElements.define('user-language-switcher', UserLanguageSwitcher);

// 全局语言管理器
window.UserLanguageManager = {
    // 获取当前语言
    getCurrentLanguage: function() {
        const switcher = document.querySelector('user-language-switcher');
        return switcher ? switcher.getCurrentLanguage() : 'zh-CN';
    },
    
    // 设置语言
    setLanguage: function(langCode) {
        const switcher = document.querySelector('user-language-switcher');
        if (switcher) {
            switcher.setLanguage(langCode);
        }
    },
    
    // 获取翻译文本（简化版）
    t: function(key, params = {}) {
        const currentLang = this.getCurrentLanguage();
        
        // 这里应该从语言包中获取翻译
        // 简化实现，实际项目中应该使用完整的i18n库
        const translations = {
            'zh-CN': {
                'home': '首页',
                'products': '产品',
                'blog': '博客',
                'about': '关于我们',
                'contact': '联系我们'
            },
            'zh-TW': {
                'home': '首頁',
                'products': '產品',
                'blog': '部落格',
                'about': '關於我們',
                'contact': '聯絡我們'
            },
            'en-US': {
                'home': 'Home',
                'products': 'Products',
                'blog': 'Blog',
                'about': 'About',
                'contact': 'Contact'
            },
            'en-GB': {
                'home': 'Home',
                'products': 'Products',
                'blog': 'Blog',
                'about': 'About',
                'contact': 'Contact'
            },
            'ja-JP': {
                'home': 'ホーム',
                'products': '製品',
                'blog': 'ブログ',
                'about': '会社概要',
                'contact': 'お問い合わせ'
            },
            'ko-KR': {
                'home': '홈',
                'products': '제품',
                'blog': '블로그',
                'about': '회사소개',
                'contact': '연락처'
            },
            'fr-FR': {
                'home': 'Accueil',
                'products': 'Produits',
                'blog': 'Blog',
                'about': 'À propos',
                'contact': 'Contact'
            },
            'de-DE': {
                'home': 'Startseite',
                'products': 'Produkte',
                'blog': 'Blog',
                'about': 'Über uns',
                'contact': 'Kontakt'
            },
            'es-ES': {
                'home': 'Inicio',
                'products': 'Productos',
                'blog': 'Blog',
                'about': 'Acerca de',
                'contact': 'Contacto'
            },
            'es-MX': {
                'home': 'Inicio',
                'products': 'Productos',
                'blog': 'Blog',
                'about': 'Acerca de',
                'contact': 'Contacto'
            },
            'pt-BR': {
                'home': 'Início',
                'products': 'Produtos',
                'blog': 'Blog',
                'about': 'Sobre',
                'contact': 'Contato'
            },
            'pt-PT': {
                'home': 'Início',
                'products': 'Produtos',
                'blog': 'Blog',
                'about': 'Sobre',
                'contact': 'Contato'
            },
            'ru-RU': {
                'home': 'Главная',
                'products': 'Продукты',
                'blog': 'Блог',
                'about': 'О нас',
                'contact': 'Контакты'
            },
            'ar-SA': {
                'home': 'الرئيسية',
                'products': 'المنتجات',
                'blog': 'المدونة',
                'about': 'من نحن',
                'contact': 'اتصل بنا'
            },
            'hi-IN': {
                'home': 'होम',
                'products': 'उत्पाद',
                'blog': 'ब्लॉग',
                'about': 'हमारे बारे में',
                'contact': 'संपर्क करें'
            },
            'th-TH': {
                'home': 'หน้าแรก',
                'products': 'สินค้า',
                'blog': 'บล็อก',
                'about': 'เกี่ยวกับเรา',
                'contact': 'ติดต่อเรา'
            },
            'vi-VN': {
                'home': 'Trang chủ',
                'products': 'Sản phẩm',
                'blog': 'Blog',
                'about': 'Về chúng tôi',
                'contact': 'Liên hệ'
            }
        };
        
        const langTranslations = translations[currentLang] || translations['zh-CN'];
        return langTranslations[key] || key;
    }
};

// 页面加载完成后初始化语言管理器
document.addEventListener('DOMContentLoaded', function() {
    // 自动初始化页面中的语言切换器
    const switchers = document.querySelectorAll('user-language-switcher');
    switchers.forEach(switcher => {
        if (!switcher.initialized) {
            switcher.initialized = true;
        }
    });
    
    // 监听语言切换事件，更新页面内容
    document.addEventListener('languageChanged', function(e) {
        console.log('Language changed to:', e.detail.language);
        // 这里可以触发页面内容的重新渲染
    });
});